﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Xml.Linq;
using System.Web.Script.Serialization;
using System.Xml.XPath;

namespace Jukebox
{
    public class Getartist: IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            //throw new NotImplementedException();
            context.Response.ContentType = "application/json";

            string artistName = context.Request.Form["Artist"];
            string limit = context.Request.Form["Limit"];

            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://ws.audioscrobbler.com/2.0/?method=artist.search&limit=" + limit + "&artist=" + artistName + "&api_key=710c97512d10ba9c106b909baf975345");

            // execute the request
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();

            XDocument doc = XDocument.Load(responseStream);
            responseStream.Close();
            responseStream.Dispose();

            var slice = from artist in doc.XPathSelectElements("//artist")
                        select new
                        {
                            Name = artist.Element("name").Value,
                            MbId = artist.Element("mbid").Value
                        };

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string jsonstr = serializer.Serialize(slice);
            context.Response.Write(jsonstr);
        }
    }
}